
#! /usr/bin/python

import sys
import os
import time
import random
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
     #   self.info=[{"Recurso":"Restaurant","Nombre":"Restaurante1","type":"Italiano","Calle":"lacalle"}]



    def _process(self):
     pass
class MyOrganization(Bureaucracy.Bureaucracy):
    def _process(self):
        time.sleep(2000)

class MyUnit(Unit.Hierarchy):
    def onStart(self):
        #time.sleep(10)
        template = Behaviour.ACLTemplate()
        template.setProperty("from",self.name)
        template.setPerformative("inform")
        template.setOntology("spade:x:unit")
        t = Behaviour.MessageTemplate(template)
        self.gotoBehaviour=self.GotoBehaviour(self)
        self.myAgent.addBehaviour(self.gotoBehaviour, t)
        info=eval(self.getGoal())
        while not info:
            info=eval(self.getGoal())
        #print info
        self.manager=info["manager"]
        print "Dentro de la unidad:"+self.name

    class GotoBehaviour(Behaviour.Behaviour):
        def __init__(self,unit):
            self.unit=unit
            Behaviour.Behaviour.__init__(self)

        def _process(self):
            m= self._receive(True)
            if m and m.getProperty("from")==self.unit.name:
                unitName=m.getContent().split(":")[1]
                u=MyUnit(self.myAgent, nick=self.myAgent.nick, password="pass", name=unitName)
                print "Soy ",self.myAgent.getAID().getName(),"Dentro de la unidad:",self.unit.name,"Tratando de entrar en ",unitName
                d=[{"name":"rol","value":"meteorology information sources"},{"name":"type","value":["Presion",self.myAgent.info[0]["type"],self.myAgent.info[0]["Subtype"]]}]
                entry=self.unit.requestEntryUnit(unitName,d)
                while not entry:
                   entry=self.unit.requestEntryUnit(unitName,d)
                if entry:
                    self.unit.joinUnit(u)
                    self.myAgent.removeBehaviour(self)

    def _process(self):
        time.sleep(2)
        if self.state!="unavailable":
            ans=ACLMessage.ACLMessage()
            ans.setPerformative("inform")
            ans.setSender(self.myAgent.getAID())
            #ans.addReceiver(self.manager)
            ans.setOntology("Meteorology")
            temp=3+(random.random()*2-1)
            ans.setContent(str({"Presion":temp}))
            self.sendPrivateMessage(ans,self.manager)
            #print "Soy ",self.myAgent.getAID().getName()," envio a "+self.manager+" la respuesta ",ans
            aid=AID.aid(self.myAgent.manager,["xmpp://"+self.myAgent.manager])
            ans.addReceiver(aid)
            self.myAgent.send(ans)
        else:
            self.myAgent.removeBehaviour(self)
            """mens=self.receiveMessage()
            while not mens and self.state!="unavailable":
              mens=self.receiveMessage()
            content=[]
            if mens:
                print mens
                for i in self.myAgent.info:
                    recurso=mens.getContent().split(":")[0]
                    type=mens.getContent().split(":")[1]
                    print recurso,type
                    if i["type"]==type and recurso==i["Recurso"]:
                        content.append(i)
                if content==[]:
                    content=""
                ans=ACLMessage.ACLMessage()
                ans.setPerformative("inform")
                ans.setSender(self.myAgent.getAID())
                ans.addReceiver(mens.getSender())
                ans.setContent(str(content))
                ans.setConversationId(mens.getConversationId())
                self.sendPrivateMessage(ans,mens.getSender().getName())
                print "Soy ",self.myAgent.getAID().getName()," envio a ",ans.getReceivers()[0].getName()," la respuesta ",ans
"""


if __name__ == "__main__":
    a="siteb"
    if len(sys.argv)>1:
        max=sys.argv[1]
    else: max=5
    max=int(max)+1
    for n in xrange(1,max):
        agent = a+str(n)+"@apolo.dsic.upv.es"
        #agent = "agent@thx1138.dsic.upv.es"
        #agent = "agent@tatooine.dsic.upv.es"
        b = Example(agent,"pasword")
        l=["A","B","C"]
        aux=["1","2","3"]
        i=random.randint(0,2)
        j=random.randint(0,2)
        b.info=[{"Recurso":"Presion","Nombre":"Presion"+str(n),"type":"ZoneP"+l[i],"Subtype":"AreaP"+l[i]+aux[j]}]
        b.nick="fuenteB"+str(n)
        b.start()
        #print "Agent "+agent+" registering"
        time.sleep(2)
        lista= b.getOrganizationList()
        #print lista
        for i in lista:
            info=b.getOrganizationInfo(i)
            goal=info["goal"]
            g=eval(goal)
            if g.has_key("needs") and g["needs"]=="meteorology information sources":
                o=MyOrganization(b,nick=b.nick, name=i)
                b.joinOrganization(o)
                l=o.getUnitList()
                b.manager=info["manager"]
                #print l
                for u in l:
                    info=o.getUnitInfo(u)
                    if info["type"]=="Hierarchy" and eval(info["goal"])["needs"]=="meteorology information sources":
                        unit=MyUnit(b, nick=b.nick, password="pass", name=u)
                        d=[{"name":"rol","value":"meteorology information sources"},{"name":"type","value":["Presion",b.info[0]["type"],b.info[0]["Subtype"]]}]
                        entry=o.requestEntryUnit(u,d)
                        if not entry:
                           entry=o.requestEntryUnit(u,d)
                        if entry:
                            o.joinUnit(unit)







